from exts import db
from werkzeug.security import generate_password_hash,check_password_hash
from datetime import datetime

class CMSPermission(object):
    #拥有所有权限，255
    ALL_PERMISSION = 0b11111111
    #访问者权限
    VISTOR =         0b00000001
    #管理帖子权限
    POSTER =         0b00000010
    #管理评论的权限
    COMMENTER =      0b00000100
    #管理板块的权限
    BOARDER =        0b00001000
    #管理前台用户的权限
    FRONTUSER =      0b00010000
    #管理后台用户的权限
    CMSUSER =        0b00100000
    #开发者权限，至高无上
    ADMIN =          0b01000000

cms_role_user = db.Table(
    'cms_role_user',
    db.Column('cms_role_id',db.Integer,db.ForeignKey('cms_role.id'),primary_key=True),
    db.Column('cms_user_id',db.Integer,db.ForeignKey('cmsuser.id'),primary_key=True)
)


class CMSRole(db.Model):
    __tablename_ = 'cms_role'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50), nullable=False)
    desc = db.Column(db.String(200))
    create_time = db.Column(db.DATETIME,default=datetime.now)
    permissions = db.Column(db.Integer,default=CMSPermission.VISTOR)

    users = db.relationship('CMSUser',secondary=cms_role_user,backref='roles')

class CMSUser(db.Model):
    __tablename__ = 'cmsuser'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    username = db.Column(db.String(50),nullable=False)
    _password = db.Column(db.String(100),nullable=False)
    email = db.Column(db.String(50),nullable=False,unique=True)
    join_time = db.Column(db.DateTime,default=datetime.now)

    # self.password 就相当于执行了self._password
    def __init__(self,username,password,email):
        self.username = username
        self.password = password
        self.email = email
    # 讲一个方法转换为属性，直接可以访问
    @property
    def password(self):
        return self._password

    # 与property 搭配使用，直接访问这个属性
    @password.setter
    def password(self,raw_password):
        self._password = generate_password_hash(raw_password)
    # 将传进来的密码进行相同的‘盐’，与之前生成的密码匹配，返回TRUE Or FALSE
    def check_password(self,raw_password):
        result = check_password_hash(self.password,raw_password)
        return result
    @property
    def permissons(self):
        if not self.roles:
            return 0
        all_permissions = 0
        for role in self.roles:
            permissions = role.permissions
            all_permissions |= permissions
        return all_permissions

    def has_permission(self,permission):
        # all_permissions = self.permissons
        # result = all_permissions&permission == permission
        # if result:
        #     print('具有%s权限' % permission)
        # else:
        #     print('不具有%s权限' % permission)
        return self.permissons & permission == permission

    @property
    def is_developer(self):
        return self.has_permission(CMSPermission.ALL_PERMISSION)

